package com.shuzijun.leetcode.editor.cn;
public class KthLargestElementInAnArray{
    public static void main(String[] args) {
         Solution solution = new KthLargestElementInAnArray().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums.length < k) return -1;
        return quickSort(nums,0,nums.length-1,k);
    }

        private int quickSort(int[] nums, int p, int r, int k) {
            if (p > r) return -1;
            int q = partition(nums,p,r);
            if (q-p+1 == k){
                return nums[q];
            } else if (q - p + 1 < k) {
                return quickSort(nums,q+1,r,k-(q-p+1));
            }else {
                return quickSort(nums,p,q-1,k);
            }
        }

        private int partition(int[] nums, int p, int r) {
            int i = p-1;
            int j = p;
            while (j < r){
                if (nums[j] > nums[r]){
                    swap(nums,j,i+1);
                    i++;
                }
                j++;
            }
            swap(nums,i+1,r);
            return i+1;
        }

        private void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        }
//leetcode submit region end(Prohibit modification and deletion)

}